<?php if( ! defined('BASEPATH')) exit('No direct script access allowed');
/********************
 *@param function:OplusCms 後臺 產品
 *@param datetime 2012-01-12
 *@param author solgh
 ********************/
class Products extends Admins_Controller {

  private $data=array();
  private $unique_id;
  public function __construct(){
    parent::__construct();
    $this->data['currentPage']='manages';
    $this->load->model('products_mdl');
    $this->data['format_time']=$this->settings['default_time'];
    $this->data['default_language']=$this->settings['default_language'];
    //查詢語言
    $this->load->model('languages_mdl');
    $this->data['languages']=$this->languages_mdl->get_core_languages(array('status'=>1));
    //產品分類
    $this->load->model('categorys_mdl');
    $data=array('language_id'=>$this->settings['default_language'],'parent_id'=>0,'status'=>1);
    $this->data['categorys']=$this->categorys_mdl->getCategories($data);

    //產品單位
    $this->load->model('productunits_mdl');
    $this->data['productunits']=$this->productunits_mdl->get_productunits(array('language_id'=>$this->settings['default_language']));    
    $this->data['lang'] =$this->lang->language;
  }

  public function index(){
    $this->get_list();
    $this->load->view('admins/products_list_view',$this->data);
  }

  //獲取列表
  private function get_list(){
    $page = $this->input->get('p',TRUE);
    $page = (!empty($page) && is_numeric($page)) ? intval($page) : 1;
    $limit = $this->settings['default_admin_limit'];
    //$limit =1;
    $offset = ($page - 1) * $limit;
    if($offset < 0){
      redirect('admins/products');
    }
    $url_query=$_SERVER['QUERY_STRING'];
    // 保留查詢參數;
    $cookie = array(
        'name'   => 'url_query',
        'value'  => base64_encode($url_query),
        'expire' => '0',
        'path'   => '/',
    );
    $this->input->set_cookie($cookie);

    if(!empty($url_query)){
      $url_query=preg_replace('/&p=(\d+)/','',$url_query);
    }
    $this->data['title']=$this->input->get('title');
    $this->data['category_id']=$this->input->get('category_id');

    $this->data['field']=$this->input->get('field');
    $this->data['sort']=$this->input->get('sort');
    $this->data['field']=!empty($this->data['field'])?$this->data['field']:'n.add_time';
    $this->data['sort']=!empty($this->data['sort'])?$this->data['sort']:'desc';

    $data=array(
      'language_id'=>$this->settings['default_language'],
      'limits'=>$limit,
      'offset'=>$offset,
    );
    $data=!empty($this->data['title'])?array_merge($data,array('title'=>trim($this->data['title']))):$data;
    $data=!empty($this->data['category_id'])?array_merge($data,array('category_id'=>trim($this->data['category_id']))):$data;

    $data=!empty($this->data['field'])?array_merge($data,array('field'=>$this->data['field'])):$data;
    $data=!empty($this->data['sort'])?array_merge($data,array('sort'=>strtoupper($this->data['sort']))):$data;

    $this->data['lists_count']=$this->products_mdl->totle_products($data);

    $pagination = '';
    if($this->data['lists_count'] > $limit)
    {
      $this->dpagination->currentPage($page);
      $this->dpagination->items($this->data['lists_count']);
      $this->dpagination->limit($limit);
      $this->dpagination->adjacents(5);
      $this->dpagination->target(site_url('admins/products').'?'.$url_query);
      $this->dpagination->parameterName('p');
      $this->dpagination->nextLabel($this->data['lang']['orders_lable_19']);
      $this->dpagination->PrevLabel($this->data['lang']['orders_lable_18']);
      $pagination = $this->dpagination->getOutput();
    }
    $this->data['pagination'] = $pagination;
    $this->data['lists']=$this->products_mdl->get_products($data);
  }

  //添加按鈕頁面跳轉
  public function add(){
    $this->load->view('admins/products_form_view',$this->data);
  }

  //修改按鈕頁面跳轉
  public function edit($edit_id=0){
    if(!empty($edit_id)){
      $query=$this->products_mdl->get_products_by_id($edit_id);
      $this->data['edit_id']=$edit_id;
      $this->data['main_image']=$query['main_image'];
      $this->data['photo']=unserialize($query['photo']);
      $this->data['sort_order']=$query['sort_order'];
      $this->data['update_time']=$query['update_time'];
      $this->data['add_time']=$query['add_time'];
      $this->data['status']=$query['status'];
      $this->data['category_id']=$query['category_id'];
      $this->data['price']=$query['price'];
      $this->data['stock'] = $query['stock'];
      $this->data['product_unit_id']=$query['product_unit_id'];
      $this->data['old_price'] = $query['old_price'];
      $this->data['is_spec'] = $query['is_spec'];
      //products資料 descriptions
      $results=$this->products_mdl->get_langdescriptions($edit_id);

      foreach($results->result_array() as $rs){
        $this->data['descriptions'][$rs['language_id']]=$rs;
      } //end foreach;

      $this->load->view('admins/products_form_view',$this->data);
    }else{
      show_error('對不起,參數出錯!');
      exit;
    }
  }

  //執行修改或添加功能
  public function modify(){
      //print_r($_POST);
      //echo "<pre>";exit;
    $edit_id=$this->input->post('edit_id');
    $images  = $this->input->post('photo');
    $attrs = $this->input->post('attrItems');
    $this->unique_id=$edit_id;
    $this->_load_validation_rules();
    if ($this->form_validation->run() == FALSE){
      $this->data['error']=true;
      $this->load->view('admins/products_form_view',$this->data);
    }else{
        print_r($_POST);
        echo "<pre>";exit;
      $update_time=$this->input->post('update_time');
      $add_time=$this->input->post('add_time');
      // $add_time=time();
      $data['general']=array(
        'sort_order'=>$this->input->post('sort_order'),
        'main_image'=>$this->input->post('main_image'),
        'photo' => serialize($images),
        'category_id'=>$this->input->post('category_id'),
        'price'=>$this->input->post('price'),
        'old_price' => $this->input->post('old_price'),
        'stock' => (int)$this->input->post('stock'),
        'product_unit_id'=>$this->input->post('product_unit_id'),
        'update_time'=>!empty($update_time)?strtotime($update_time):time(),
        'add_time'=>!empty($add_time)?strtotime($add_time):time(),
        'status'=> (int)$this->input->post('status'),
        'is_spec' => (int)$this->input->post('is_spec'),
      );
      //var_dump($data['general']);exit;
      //多語言描述
      $data['descriptions']=$this->input->post('descriptions');
      if(!empty($edit_id)){
        $operator_title='修改產品->'.$data['descriptions'][$this->settings['default_language']]['title'];
        $action='修改';
        $result=$this->products_mdl->edit_products($data,$edit_id);
      }else{
        $operator_title='新增產品->'.$data['descriptions'][$this->settings['default_language']]['title'];
        $action='新增';
        $result=$this->products_mdl->add_products($data);
        $edit_id = $this->products_mdl->insert_id;
      }
      $base = array();
      $items = $this->input->post('item');

      if($result){
        $i=0;
        foreach($items as $key=>$item){
          //if((float)$item['price'] <= 0) $item['price']= (float)$this->input->post('price')+$this->specs_mdl->get_items_price($key);
          $base[$i]['product_id'] = $edit_id;
          $base[$i]['spec_key'] = $key;
          $base[$i]['spec_name'] = $item['spec_name'];
          $base[$i]['price'] = (float)$item['price'];
          $i++;
        }
        $this->products_mdl->addItemPrice($base,$edit_id);
        /*添加属性*/
        $attrBase = array();
        if(isset($attrs) && count($attrs) > 0){
            
            $k=0;
            foreach ($attrs as $key => $value) {
              list($spec_id,$item_id) = explode("_", $key);
              $attrBase[$k]['product_id'] =$edit_id; 
              $attrBase[$k]['spec_id'] =$spec_id; 
              $attrBase[$k]['item_id'] =$item_id; 
              $attrBase[$k]['num'] = 1; 
              $k++;
            }
        }
         $this->products_mdl->addAttrItem($attrBase,$edit_id);

      }
      
      $this->operator_log($operator_title,$action,$result);
      $msg = $result > 0?$this->data['lang']['global_lable_48']:$this->data['lang']['global_lable_49'];
      $notify = $result > 0?'success':'error';
      $this->nsession->set_flashdata($notify, $msg);
      $redirect=site_url('admins/products').$this->settings['url_query'];//獲取列表篩選參數
      redirect($redirect);
    }
  }

  //上傳主圖片.
  private function _upload_images($file_name='',$old_image=''){
    if(isset($_FILES[$file_name]['name']) && !empty($_FILES[$file_name]['name'])){
      $upload_path='uploads/products/';
      Imagelib::mkdir_file($upload_path); //創建路徑
      $allowed_types=array('jpg','png','gif','jpeg');
      $max_size='80240000';
      $temp_file=$_FILES[$file_name]['tmp_name']; //臨時文件
      $f_name=$_FILES[$file_name]['name'];
      $f_size=$_FILES[$file_name]['size'];
      $x = explode('.', $f_name);
      $f_extention=strtolower(end($x));
      if(!empty($f_extention) && in_array($f_extention,$allowed_types) && $f_size<=$max_size){
        $filename = md5(uniqid(mt_rand())).'.'.$f_extention; //新名字
        $product_file_name=$upload_path.$filename;
        if(move_uploaded_file($temp_file,$product_file_name)){
          if(!empty($old_image) && file_exists($old_image)){
            Imagelib::delete_image($old_image); //刪除舊圖片.
            Imagelib::delete_thumb_image($old_image); //刪除舊圖片縮略圖.
          }
          return $product_file_name; //返回上傳后的新名字.
        }
      }
    }else{
      return $old_image;
    }
  }

  //執行刪除功能
  public function delete($delete_id=0){
    if(!empty($delete_id)){
      $result=$this->products_mdl->delete_products($delete_id);
      $this->operator_log('刪除產品->ID:'.$delete_id,'刪除',$result);
      $msg = $result > 0?$this->data['lang']['global_lable_48']:$this->data['lang']['global_lable_49'];
      $notify = $result > 0?'success':'error';
      $this->nsession->set_flashdata($notify, $msg);
      $redirect=site_url('admins/products').$this->settings['url_query'];//獲取列表篩選參數
      redirect($redirect);
    }else{
      show_error('對不起,參數出錯!');
      exit;
    }
  }
  
   //批量刪除
  public function delete_batch(){
     $delete_string=$this->input->get('delete_string');
     if(!empty($delete_string)){
        $del_arr=explode(',',$delete_string);
        $result=$this->products_mdl->delete_batch($del_arr);

        $this->operator_log('批量刪除產品->ID:'.$delete_string,'批量刪除',$result);

        $msg = $result > 0?$this->data['lang']['global_lable_48']:$this->data['lang']['global_lable_49'];
        $notify = $result > 0?'success':'error';
        $this->nsession->set_flashdata($notify, $msg);
        $redirect=site_url('admins/products').$this->settings['url_query'];//獲取列表篩選參數
        redirect($redirect);
      }else{
        show_error('對不起,參數出錯');
        exit;
      }
  }

  //驗證數據格式
  private function _load_validation_rules(){
      $this->form_validation->set_rules('category_id','所屬類別','trim|required|numeric|max_length[11]');
      $this->form_validation->set_rules('product_unit_id','產品單位','trim|required|numeric|max_length[11]');
      $this->form_validation->set_rules('price','價格','trim|required|numeric|max_length[18]');
      $this->form_validation->set_rules('add_time','添加時間','trim|max_length[20]');
      $this->form_validation->set_rules('update_time','修改時間','trim|max_length[20]');
      $this->form_validation->set_rules('sort_order','排序','trim|numeric|max_length[10]');
      $this->form_validation->set_rules('status','狀態','trim|required|numeric|max_length[1]');
      $this->form_validation->set_rules('edit_id','修改ID','trim|numeric');
      $this->form_validation->set_rules('main_image','封面圖片','trim|max_length[100]');
      //$this->form_validation->set_rules('photo','圖集','trim|max_length[300]');

      //多語言判斷
      foreach($this->data['languages']->result_array() as $lg){
          $title        ='descriptions['.$lg["id"].'][title]';
          $introduction ='descriptions['.$lg["id"].'][introduction]';
          $number ='descriptions['.$lg["id"].'][number]';
          $content      ='descriptions['.$lg["id"].'][content]';
          $this->form_validation->set_rules($title,$lg['name'].' 標題','trim|required|max_length[200]');
          $this->form_validation->set_rules($introduction,$lg['name'].' 內容簡介','trim|max_length[300]');
          $this->form_validation->set_rules($number,$lg['name'].' 編號','trim|required|max_length[200]');
          $this->form_validation->set_rules($content,$lg['name'].' 內容','trim');
      }
  }

  //重置檢視數
  public function reset($reset_id=''){
    if(!empty($reset_id)){
      $data['general']=array('view_num'=>0);
      $result=$this->products_mdl->edit_products($data,$reset_id);
      $this->operator_log('重置產品檢視數->ID:'.$reset_id,'重置',$result);
      $msg = $result > 0?$this->data['lang']['global_lable_48']:$this->data['lang']['global_lable_49'];
      $notify = $result > 0?'success':'error';
      $this->nsession->set_flashdata($notify,$msg);
      $redirect=site_url('admins/products').$this->settings['url_query'];//獲取列表篩選參數
      redirect($redirect);
    }else{
      show_error('對不起,參數出錯!');
      exit;
    }
  }

   //獲取類別
  private function _get_category(){
     $this->load->model('categorys_mdl');
     $data=array('language_id'=>$this->settings['default_language'],'status'=>1);
     $this->data['categorys']=$this->categorys_mdl->get_producttype($data);
  }

  //--Banner廣告--//
  //相簿功能
  public function album($album_id=0){
    if(!empty($album_id)){
      $this->data['album_id']=$album_id;
      $album_title=$this->input->get('title');
      $album_title=!empty($album_title)?$album_title:$this->input->cookie('album_title');
      $cookie = array(
          'name'   => 'album_title',
          'value'  => $album_title,
          'expire' => '0',
          'path'   => '/',
      );
      $this->input->set_cookie($cookie); 
      $this->data['title']=$album_title;
      
      $page = $this->input->get('p',TRUE);
      $page = (!empty($page) && is_numeric($page)) ? intval($page) : 1;
      $limit = $this->settings['default_admin_limit'];  
      $offset = ($page - 1) * $limit;
      if($offset < 0){
        redirect('admins/products/album/'.$album_id);
      }
      $url_query=$_SERVER['QUERY_STRING'];
      if(!empty($url_query)){
        $url_query=preg_replace('/&p=(\d+)/','',$url_query);
      }
      $data=array('album_id'=>$album_id,'limits'=>$limit,'offset'=>$offset);
      
      $this->data['lists_count']=$this->products_mdl->totle_images($data);
      $pagination = '';
      if($this->data['lists_count'] > $limit)
      {
        $this->dpagination->currentPage($page);
        $this->dpagination->items($this->data['lists_count']);
        $this->dpagination->limit($limit);
        $this->dpagination->adjacents(5);
        $this->dpagination->target(site_url('admins/products/album/'.$album_id).'?'.$url_query);
        $this->dpagination->parameterName('p');
        $this->dpagination->nextLabel($this->data['lang']['orders_lable_19']);
        $this->dpagination->PrevLabel($this->data['lang']['orders_lable_18']);
        $pagination = $this->dpagination->getOutput();
      }
      $this->data['pagination'] = $pagination;
            
      $this->data['images']=$this->products_mdl->get_images($data);
      $this->load->view('admins/products_images_view',$this->data);
    }else{
      show_error('對不起,參數出錯!');
      exit;
    }
  }
   
   //相簿圖片刪除
   public function album_delete($image_id='',$album_id='',$images=''){
     if(!empty($image_id) && !empty($album_id)){
        $images=$this->input->get('images');
        if(!empty($images) && file_exists($images)){
           Imagelib::delete_image($images); //刪除舊圖片.
           Imagelib::delete_thumb_image($images); //刪除舊圖片縮略圖.
         }
         $result=$this->products_mdl->delete_image($image_id);
         $this->operator_log('刪除產品相簿圖片->ID:'.$image_id,'刪除',$result);
         $msg = $result > 0?$this->data['lang']['global_lable_48']:$this->data['lang']['global_lable_49'];
         $notify = $result > 0?'success':'error';
         $this->nsession->set_flashdata($notify, $msg);
         redirect("admins/products/album/".$album_id);         
     } 
   }
   
  //執行上傳相簿圖片
  public function album_modify(){
     $modify_method=$this->input->post('modify_method'); //執行方法.
     $this->_load_validation_album($modify_method);
     $album_id=$this->input->post('album_id');
     if($this->form_validation->run() == FALSE){
         $this->data['error']=true; 
         $this->album($album_id);
      }else{
         $old_images=$this->input->post('old_images');
         $images=$this->_upload_images('images',$old_images); //主圖片的上傳或修改.
         $desc=$this->input->post('description');
         $data=array(
            'images'=>$images,
            'sort_order'=>$this->input->post('sort_order'),
            'description'=>!empty($desc)?json_encode($desc):NULL,
            'category_id'=>$album_id
          );
          $images_id=$this->input->post('images_id');
          if($images_id>0){
             $operator_title='修改產品相簿圖片->'.$images;
             $action='修改';
             $result=$this->products_mdl->edit_images($data,$images_id);
          }else{
             $operator_title='新增產品相簿圖片->'.$images;
             $action='新增';
             $result=$this->products_mdl->add_images($data);
          }
         $this->operator_log($operator_title,$action,$result);
         $msg = $result > 0?$this->data['lang']['global_lable_48']:$this->data['lang']['global_lable_49'];
         $notify = $result > 0?'success':'error';
         $this->nsession->set_flashdata($notify, $msg);
         redirect("admins/products/album/".$album_id);
      }
  }
  
   //批量上傳圖片
  public function album_batch(){
      $album_id=$this->input->post('album_id');
      $images=$this->input->post('images');
      if(!empty($album_id) && !empty($images)){
        // $description=$this->input->post('description');
        $sort_order=$this->input->post('sort_order');
        $result=0;
        for ($i=0; $i < count($images); $i++) {
          $desc=array();
          foreach ($this->data['languages']->result_array()  as $rs) {
            $description=$this->input->post('description_'.$rs['id']);
            // print_r($description[$i]);
            $desc[$rs['id']]=$description[$i];
          } 
          $data=array(
            'images'=>$images[$i],
            'sort_order'=>$sort_order[$i],
            'description'=>!empty($desc)?json_encode($desc):NULL,
            'category_id'=>$album_id
          );
          $result+=$this->products_mdl->add_images($data);
        }
        $this->operator_log('批量上傳產品相簿圖片->ID:'.$album_id,'批量上傳',$result);
        $msg = $result > 0?$this->data['lang']['global_lable_48']:$this->data['lang']['global_lable_49'];
        $notify = $result > 0?'success':'error';
        $this->nsession->set_flashdata($notify, $msg);
        redirect("admins/products/album/".$album_id);
      }
   }
   
  //驗證相簿上傳的數據格式
  private function _load_validation_album($modify_method='add'){
    if($modify_method=='add'){
       $this->form_validation->set_rules('album_id','相簿ID','required|trim|numeric');
       $this->form_validation->set_rules('images','圖片','callback__images_check');
       $this->form_validation->set_rules('sort_order','排序','required|trim|numeric');
       $this->form_validation->set_rules('description[]','描述','trim');
    }else{
       $this->form_validation->set_rules('album_id','相簿ID','required|trim|numeric');
       $this->form_validation->set_rules('images_id','相片ID','required|trim|numeric');
       $this->form_validation->set_rules('old_images','舊相片','required|trim');
       $this->form_validation->set_rules('sort_order','排序','required|trim|numeric');
       $this->form_validation->set_rules('description[]','描述','trim');   
    }
  }
  //驗證圖片
  function _images_check($str){
    $allowed_types=array('jpg','png','gif','jpeg');
    $temp_file=$_FILES['images']['tmp_name'];
    $f_name=$_FILES['images']['name'];
    $x = explode('.', $f_name);
    $f_extention=strtolower(end($x));
    if(!empty($temp_file) && $f_name && in_array($f_extention,$allowed_types)){
      return TRUE;
    }else{
      $this->form_validation->set_message('_images_check', '圖片不能為空,或格式不正確!');
       return FALSE;
    }
  }
  //遍歷二級
  public function _get_up($category_id){
    if(!empty($category_id)&&!empty($category_id)){
      $this->load->model('categorys_mdl');
      $up=$this->categorys_mdl->totle_categorys(array('parent_id'=>$category_id));
      if($up>0)
        return true;
      else
        return false;
    }
  }
}